package com.quiz.quazz.client;

/* The java.net package contains the basics needed for network operations. */
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * The SocketClient class is a simple example of a TCP/IP Socket Client.
 */

public class Client {

	private int port;

	/** the server address */
	private String hostIP;

	private OutputStreamWriter osw;

	private Socket connection;

	public Client(String ipAdress, int port, String message) {
		this.hostIP = ipAdress;
		this.port = 50000 + port;

		try {
			connect();
			registerPlayer(message);
			openInputStream();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @param message the action command
	 */
	public void openInputStream() {
		StringBuffer instr = new StringBuffer();
		try {
			BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
			InputStreamReader isr = new InputStreamReader(bis, "US-ASCII");

			int c;
			while ((c = isr.read()) != 13)
				instr.append((char) c);
			String receivedMessage = instr.toString();
			interpretMessage(receivedMessage);
		} catch (Exception f) {
			System.out.println("IOException: " + f);
		}
	}

	private void interpretMessage(String receivedMessage) {
		System.out.println(receivedMessage);
	}

	private void registerPlayer(String message) throws IOException {
		osw.write(message + (char) 13);
		osw.flush();
	}

	private void connect() throws UnknownHostException, IOException, UnsupportedEncodingException {
		connection = new Socket(hostIP, port);
		BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());
		osw = new OutputStreamWriter(bos, "US-ASCII");
	}

}